/*
 * JGO2RDF creates a RDF representation of GAF2 files, which are automatically sourced from GO ftp site.
 * Copyright (C) 2012 Matthew M. Hindle & Artem Lysenko
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package uk.co.jgo2rdf.goa.deligates;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.RDFS;
import org.apache.log4j.Logger;
import uk.co.jgo2rdf.exception.AccessionNonConformentException;
import uk.co.jgo2rdf.goa.gp2protein.EntityType;
import uk.co.jgo2rdf.rdf.lsrn.LSRNVocab;
import uk.co.jgo2rdf.rdf.refseq.RefSeqFactory;
import uk.co.jgo2rdf.rdf.sio.SIOVocab;

import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: mhindle
 * Date: 21/02/12
 * Time: 16:57
 * To change this template use File | Settings | File Templates.
 */
public class GeneBankRDFizer implements EntityRDFizer {

    private static final Logger log = Logger.getLogger(GeneBankRDFizer.class);

    private static Pattern proteinRegex = Pattern.compile("[A-Z]{3}\\d{5}(\\.\\d+)?");
    private static Pattern ntRegex = Pattern.compile("([A-Z]\\d{5}|[A-Z]{2}\\d{6})(\\.\\d+)?");
    private static Pattern wgsRegex = Pattern.compile("[A-Z]{4}\\d{2}(\\.\\d+)?");
    private static Pattern mgaRegex = Pattern.compile("[A-Z]{5}\\d{7}(\\.\\d+)?");

    public static boolean isGeneBankProtein(String accession) {
        return proteinRegex.matcher(accession).matches();
    }

    public static boolean isGeneBankNuclotide(String accession) {
        return ntRegex.matcher(accession).matches();
    }

    public static boolean isGeneBankWGS(String accession) {
        return wgsRegex.matcher(accession).matches();
    }


    public static boolean isGeneBankMGA(String accession) {
        return mgaRegex.matcher(accession).matches();
    }

    public static boolean isGeneBank(String accession) {
        return isGeneBankProtein(accession)
                || isGeneBankNuclotide(accession)
                || isGeneBankWGS(accession)
                || isGeneBankMGA(accession);
    }


    @Override
    public Resource rdfize(Model jenaModel, String accession) throws Exception {
        String copy = accession;

        accession = preProcessAccession(accession);

        if (!isGeneBank(accession)) {
            if (RefSeqFactory.isRefSeqId(accession)) {
                log.debug("Sent " + accession + " to NCBI RefSeq rdfizer");
                return new RefSeqRDFizer().rdfize(jenaModel, accession);
            } else {
                throw new AccessionNonConformentException(copy + "=processed-to=>" + accession);
            }
        }

        if (accession.length() == 0) {
            throw new AccessionNonConformentException(copy + "=processed-to=>" + accession);
        }

        String uri = "http://www.ncbi.nlm.nih.gov/nuccore/";
        if (isGeneBankProtein(accession)) {
            uri = "http://www.ncbi.nlm.nih.gov/protein/";
        }

        Resource record = jenaModel.createResource(uri + accession, LSRNVocab.Genbank_Record);
        Resource identifier = jenaModel.createResource(uri + accession + "-id", LSRNVocab.Genbank_Identifier);

        record.addProperty(SIOVocab.has_attribute, identifier);
        record.addLiteral(RDFS.label, accession);
        identifier.addLiteral(SIOVocab.has_value, accession);
        identifier.addLiteral(RDFS.label, accession + "-id");

        try {
            EntityType type = getType(accession);
            if (type.equals(EntityType.DNA)) {
                Resource dna = jenaModel.createResource(SIOVocab.dna);
                record.addProperty(SIOVocab.is_about, dna);
                dna.addLiteral(RDFS.label, accession + "-dna");
                return dna;
            } else if (type.equals(EntityType.RNA)) {
                Resource rna = jenaModel.createResource(SIOVocab.rna);
                record.addProperty(SIOVocab.is_about, rna);
                rna.addLiteral(RDFS.label, accession + "-rna");
                return rna;
            } else if (type.equals(EntityType.PROTEIN)) {
                Resource protein = jenaModel.createResource(SIOVocab.protein);
                record.addProperty(SIOVocab.is_about, protein);
                protein.addLiteral(RDFS.label, accession + "-protein");
                return protein;
            }
        } catch (AccessionNonConformentException e) {
            log.warn(e);
        }
        Resource entity = jenaModel.createResource(SIOVocab.entity);
        record.addProperty(SIOVocab.is_about, entity);
        entity.addLiteral(RDFS.label, accession + "-entity");
        return entity;
    }

    @Override
    public EntityType getType(String accession) throws Exception {
        if (isGeneBankProtein(accession)) {
            return EntityType.PROTEIN;
        } else if (isGeneBankNuclotide(accession)) {
            return EntityType.DNA;
        } else if (isGeneBankWGS(accession)) {
            return EntityType.DNA;
        } else if (isGeneBankMGA(accession)) {
            return EntityType.DNA;
        }
        throw new AccessionNonConformentException(accession);
    }

    @Override
    public String preProcessAccession(String accession) {
        accession = accession.trim().toUpperCase();

        int versionIndex = accession.lastIndexOf('.');
        if (versionIndex > -1) {
            accession = accession.substring(0, versionIndex);
        }

        int dbIndex = accession.indexOf(':');
        if (dbIndex > -1) {
            accession = accession.substring(dbIndex + 1, accession.length());
        }

        return accession;
    }
}
